import paramiko
import openpyxl
import re
import time

def read_devices_from_excel(filename):
    wb = openpyxl.load_workbook(filename)
    ws = wb.active
    devices = []
    for row in ws.iter_rows(min_row=2, values_only=True):
        ip, username, password, hostname, command = row[:5]
        devices.append({
            "ip": ip,
            "username": username,
            "password": password,
            "hostname": hostname,
            "command": command
        })
    return devices

def ssh_and_run(dev):
    ip = dev["ip"]
    username = dev["username"]
    password = dev["password"]
    expected_hostname = dev["hostname"]
    command_str = dev["command"]
    if not ip:
        print("[空IP] 跳过")
        return
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, username=username, password=password, timeout=10)
        shell = ssh.invoke_shell()
        shell.send("\n")
        time.sleep(0.5)
        buff = ""
        for _ in range(10):
            time.sleep(0.2)
            if shell.recv_ready():
                buff += shell.recv(4096).decode(errors="ignore")
        m = re.search(r"[<\[]([^\]>]+)[>\]]", buff)
        if m:
            # H3C设备
            hostname = m.group(1)
            print(f"[{ip}] 实际主机名: {hostname}")
            if hostname != expected_hostname:
                print(f"[{ip}] 主机名不匹配，跳过")
                ssh.close()
                return
            # H3C只执行一条命令
            shell.send(command_str + "\n")
            time.sleep(1)
            output = ""
            while shell.recv_ready():
                output += shell.recv(4096).decode(errors="ignore")
            #print(f"[{ip}] 执行命令: {command_str}\n{output}")
        else:
            print(f"[{ip}] 未识别到主机名，跳过")
        ssh.close()
    except Exception as e:
        print(f"[{ip}] 连接失败: {e}")

if __name__ == "__main__":
    devices = read_devices_from_excel("devices.xlsx")
    for dev in devices:
        ssh_and_run(dev)
